package ch.zhaw.mini.doclet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import ch.zhaw.mini.doclet.page.PackagePage;
import ch.zhaw.mini.doclet.page.Page;

import com.sun.javadoc.Doclet;
import com.sun.javadoc.RootDoc;

/**
 * The WikiDoclet is used by Javadoc as a custom Doclet. It creates Wikimedia
 * Pages from Javadoc output and places them in a XML File specified by
 * parameter "-d" and "-f" while calling Javadoc. The WikiDoclet Class has a
 * dependency to the org.slf4j Package.
 * 
 * @author Rolf Koch (kochrol@students.zhaw.ch)
 * 
 * @version 1.0
 * 
 */
public class MiniDoclet extends Doclet {

	/**
	 * Logger Variable
	 */
	

	/**
	 * Standard doclet entry point. This method is called by Javadoc
	 * 
	 * @param root
	 *            A RootDoc object usually created by Javadoc utility
	 * @return True or False if the Doclet was successfull.
	 */
	public static boolean start(RootDoc root) {
		
		// logger = LoggerFactory.getLogger(WikiDoclet.class);
		
		// Analyse the Rootdoc Object and create the PageSet
		AnalyseRootDoc analyser = new AnalyseRootDoc(root);
	
		File f = new File("02_KlassenverantwortlichkeitenTABLE.tex");
		
		
		// Create Folders if Required
		if (f.getParent() != null) {
			new File(f.getParent()).mkdirs();
		}
		
		
		


		try {
			BufferedWriter f0 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"UTF8"));
		
			f0.write("\\begin{table}[htp]\n" +
			        "\\begin{tabular}{ | l | p{10cm} | l |}\n"+
			        "\\hline\n" +
			        " \\textbf{Name} & \\textbf{Verantwortlichkeit}  \\\\ \\hline \\hline\n");

			List<Page> pageList = analyser.getPageSet();
			for(Page p : pageList) {
				f0.write(bb(p) +" & "+p.toString()+"  \\\\ \\hline\n");
			}
			
			f0.write("\\end{tabular}\n"+
					"\\caption{Klassen Abhängigkeiten: Automatisch durch Javadoc generiert}"+
					"\\end{table}");
		
		f0.flush();
		f0.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return true;
	}
	
	public static String bb(Page p) {
		if(p instanceof PackagePage) {
			return "\\textbf{"+p.getPageTitle()+"}";
		} else {
			return p.getPageTitle().substring(p.getPageTitle().lastIndexOf(".")+1, p.getPageTitle().length());
		}
	}

	/**
	 * Returns always 2
	 * @param option
	 * @return
	 */
	public static int optionLength(String option) {
		
		return 2;
	}

}
